package com.jungle.system.application.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.jungle.common.utils.BeanCopyUtils;
import com.jungle.system.application.domain.SysApplication;
import com.jungle.system.application.domain.bo.SysApplicationBo;
import com.jungle.system.application.domain.vo.SysApplicationVo;
import com.jungle.system.application.repository.SysApplicationRepository;
import com.jungle.system.application.service.ISysApplicationService;
import com.jungle.common.core.domain.OptionVo;
import com.jungle.common.core.domain.PageQuery;
import com.jungle.common.core.page.TableDataInfo;
import com.jungle.common.utils.StringUtils;
 import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 应用管理Service业务层处理
 *
 * @author jungle
 * @date 2023-03-05
 */
@RequiredArgsConstructor
@Service
public class SysApplicationServiceImpl implements ISysApplicationService {

    private final SysApplicationRepository repository;

    /**
     * 查询应用管理
     */
    @Override
    public SysApplicationVo queryById(String id) {
        return repository.findById(id).map(v -> BeanCopyUtils.copy(v, SysApplicationVo.class)).orElse(null);
    }

    /**
     * 查询应用管理列表
     */
    @Override
    public TableDataInfo<SysApplicationVo> queryPageList(SysApplicationBo bo, PageQuery pageQuery) {
        Page<SysApplication> result = repository.findAll(getSpecification(bo), pageQuery.pageable());
        return TableDataInfo.build(result, SysApplicationVo.class);
    }

    /**
     * 查询应用管理列表
     */
    @Override
    public List<SysApplicationVo> queryList(SysApplicationBo bo) {
        return repository.findAll(getSpecification(bo)).stream()
            .map(v -> BeanCopyUtils.copy(v, SysApplicationVo.class))
            .collect(Collectors.toList());
    }

    private Specification<SysApplication> getSpecification(SysApplicationBo bo) {
        return (root, query, cb) -> {
            Map<String, Object> params = bo.getParams();
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(bo.getName())) {
                predicates.add(cb.like(root.get("name"), "%" + bo.getName() + "%"));
            }
            if (StringUtils.isNotBlank(bo.getType())) {
                predicates.add(cb.equal(root.get("type"), bo.getType()));
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };
    }

    /**
     * 新增应用管理
     */
    @Override
    public Boolean insertByBo(SysApplicationBo bo) {
        SysApplication add = BeanCopyUtils.copy(bo, SysApplication.class);
        validEntityBeforeSave(add);
        repository.saveAndFlush(add);
        bo.setId(add.getId());
        return true;
    }

    /**
     * 修改应用管理
     */
    @Override
    public Boolean updateByBo(SysApplicationBo bo) {
        SysApplication update = BeanCopyUtils.copy(bo, SysApplication.class);
        validEntityBeforeSave(update);
        return repository.save(update) != null;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysApplication entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除应用管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        repository.deleteAllById(ids);
        return true;
    }

    /**
     * 获取应用管理选项
     */
    @Override
    public List<OptionVo> optionSelect(String queryStr, String[] ids, String field, PageQuery pageQuery) {
        if (StringUtils.isNotBlank(field)) {
            return AutoComputeUtils.autoCompute(SysApplication.class, queryStr, field, pageQuery);
        }
        return repository.findAll((root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(queryStr)) {
                predicates.add(cb.like(root.get("name"), "%" + queryStr + "%"));
            }
            if (ArrayUtil.isNotEmpty(ids)) {
                predicates.add(root.get("id").in(ids));
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageQuery.pageable())
            .stream()
            .map(v -> new OptionVo(v.getId(), v.getName()))
            .collect(Collectors.toList());
    }
}
